import { createReducer, createActions } from "reduxsauce"
import Immutable from "seamless-immutable"
import _ from "lodash"
import WebIM from "@/config/WebIM"
import { I18n } from "react-redux-i18n"
import $ from 'jquery'

import CommonActions from "@/redux/CommonRedux"

/* ------------- Types and Action Creators ------------- */
const { Types, Creators } = createActions({
    updateRoster: [ "roster" ],
    prependRoster: [ "name" ],
    removeRoster: [ "name" ],
    topRoster: [ "name" ],
    // ----------------async------------------
    // get contacts list
    getContacts: () => {
        return (dispatch, getState) => {
            dispatch(CommonActions.fetching())
            WebIM.conn.getRoster({
                success: roster => {
                    console.log("======xiexie roster=====",roster);
                    getJSON(roster);
                    dispatch(Creators.updateRoster(roster))
                    dispatch(CommonActions.fetched())

                },
                error: error => {
                    //TODO ERROR
                    dispatch(CommonActions.fetched())
                }
            })
        }
    },
    // delete contact
    removeContact: id => {
        return (dispatch, getState) => {
            //loading
            dispatch(CommonActions.fetching())
            WebIM.conn.removeRoster({
                to: id,
                success: function() {
                    //loading end
                    dispatch(CommonActions.fetched())
                    dispatch(Creators.getContacts())

                    WebIM.conn.unsubscribed({
                        to: id
                    })
                },
                error: function() {
                    //TODO ERROR
                    dispatch(CommonActions.fetched())
                }
            })
        }
    },
    // add contact
    addContact: id => {
        return (dispatch, getState) => {
            const u = getState().login.username
            WebIM.conn.subscribe({
                to: id,
                message: u + I18n.t("request")
            })
        }
    }
})

export const RosterTypes = Types
export default Creators

/* ------------- Initial State ------------- */
export const INITIAL_STATE = Immutable({
    byName: null,
    names: [],
    nicknames : [],
    friends: []
})

/* ------------- Reducers ------------- */
function isFriend(v) {
    return v.subscription != "none"
}

export const updateRoster = (state, { roster }) => {
    let byName = {},
        names = [],
        byNickName = {},
        nicknames = [],
        friends = []
    roster.forEach(v => {
        byName[v.name] = v
        names = Object.keys(byName).sort()
        byNickName[v.nickname] = v
        nicknames = Object.keys(byNickName).sort()
        isFriend(v) && friends.push(v.name)  //++++++0515 xielj
       //isFriend(v) && friends.push(v.nickname)
    })
    return state.merge({
        byName,
        names,
        nicknames,
        friends
    })
}

export const prependRoster = (state, { name }) => {
    const friends = state.getIn([ "friends" ], Immutable([])).asMutable()
    friends.unshift(name)
    return state.merge({ friends })
}

export const removeRoster = (state, { name }) => {
    let friends = state.getIn([ "friends" ], Immutable([])).asMutable()
    friends = _.without(friends, name)
    return state.merge({ friends })
}

export const topRoster = (state, { name }) => {
    let friends = state.getIn([ "friends" ], Immutable([])).asMutable()
    if (friends[0] === name) return state // if already top, return directly
    friends = _.without(friends, name)
    friends.unshift(name)
    return state.merge({ friends })
}

/* ------------- Hookup Reducers To Types ------------- */
export const reducer = createReducer(INITIAL_STATE, {
    [Types.UPDATE_ROSTER]: updateRoster,
    [Types.TOP_ROSTER]: topRoster,
    [Types.PREPEND_ROSTER]: prependRoster,
    [Types.REMOVE_ROSTER]: removeRoster
})

/* ------------- Selectors ------------- */

function getJSON(obj) {
    let ids = "";
    let names = [];
    for(let v=0;v<obj.length;v++){
        let temp = obj[v].name;
        names[v] = temp;
        ids += temp.split("_")[1];
        if(v != obj.length-1){
            ids +=",";
        }
    }
    console.log("=====test=ids===",ids,names);
    var data =  ids;
    $.ajax({
        type:'get',
        url:'http://120.78.225.35:8080/xiaopu/user/getUserInfoByIds.json',
        data:{"ids":data},
        dataType:'jsonp',
        success:function(result){
            console.log("=====getJSON====",result);
            if(result){
                for(let t=0;t<result.length;t++){
                    let tt = result[t].nickname;
                    window.localStorage.setItem(names[t],tt);
                }
            }
        }
    })
};